package cn.dw.sg.mapper.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import cn.dw.sg.domain.Authority;
import cn.dw.sg.domain.Role;
import cn.dw.sg.mapper.RoleMapper;
import cn.dw.sg.utils.JdbcUtil;

public class RoleMapperImpl implements RoleMapper{
    
	private String url="jdbc:mysql://localhost:3306/sgweb??useUnicode=true&characterEncoding=utf8";
	private String user="root";
	private String password="123456";
	
	public Connection getConnection(){
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		Connection conn=null;
		try {
			conn =DriverManager.getConnection(url, user, password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	public void add(Role role) {	
		String sql="insert into role(name,role_id) values ('"+role.getName()+"',"+role.getRoleId()+") ";
		Connection conn=getConnection();
		Statement stat = null;
		try {
			stat = conn.createStatement();
			System.out.println(sql);
			stat.execute(sql);
			stat.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		
	}

	@Override
	public void update(Role role) {
		String sql="update role set name='"+role.getName()+"',role_id="+role.getRoleId()
					+" where id="+role.getId();
		Connection conn=getConnection();
		Statement stat =null;
		try {
			stat=conn.createStatement();
			System.out.println(sql);
			stat.execute(sql);
			stat.close();
			conn.close();
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
		
		
	}

	@Override
	public void delete(int id) {
		String sql="delete from role where id="+id;
		Connection conn=getConnection();
		Statement stat =null;
		try {
			stat=conn.createStatement();
			System.out.println(sql);
			stat.execute(sql);
			stat.close();
			conn.close();
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
	}

	@Override
	public List<Role> query(Role role) {
		String sql="select id,name as name,role_id as roleId from role";
		System.out.println(sql);
		List<Object> results =JdbcUtil.excuteQuery(sql, Role.class);
		List<Role> lists=new ArrayList<>();
		for(Object b : results) {
			Role temp = (Role)b;
			lists.add(temp);
		}
		return lists;
	}
}
